package net.ksic.common;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;

public class Test {
	public InputStream send(String url, String get, String post,
			HashMap<String, InputStream> file) {
		try {
			if (get != null) {
				// url에 get처리
				StringBuffer sb = new StringBuffer();
				String book = "";

				// 1. 북마크가 있다면 미리 분리해두자
				if (url.indexOf("#") > -1) {
					String[] urlmark = url.split("#");
					url = urlmark[0];
					book = urlmark[1];
				}

				// 2. cgi문자열 생성
				sb.append(url).append("?");
				String[] ayget = get.split(",");
				for (int i = 0, j = ayget.length; i < j;) {
					sb.append(URLEncoder.encode(ayget[i++], "UTF-8"))
							.append("=")
							.append(URLEncoder.encode(ayget[i++], "UTF-8"));
					if (i < j - 1)
						sb.append("&");
				}

				// 3. 북마크가 있었으면 다시 붙여주고
				if (book != null) {
					sb.append("#").append(book);

					// 4. url을 대체한다.
					url = sb.toString();
				}

			}

			HttpURLConnection conn;
			conn = (HttpURLConnection) new URL(url).openConnection();

			// 1. 타임아웃 설정
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);

			// 2. 요청편집허가
			conn.setDoInput(true);
			conn.setDoOutput(true);

			// 3. 캐쉬를 꺼두자
			conn.setUseCaches(false);

			// 4. keepalive는 도움이 된다
			conn.setRequestProperty("Connection", "Keep-Alive");

			// 5. 요청 메서드를 판별하자.
			if (post != null || file != null) {
				conn.setRequestMethod("POST");
			} else {
				conn.setRequestMethod("GET");
			}
			
			conn.setRequestProperty("Accept-Encoding", "gzip");

			if (file != null) {
				conn.setRequestProperty("Content-Type",
						"multipart/form-data, boundary=-----------");
				// file, post 처리

				DataOutputStream dos;
				dos = new DataOutputStream(conn.getOutputStream());

				if (post != null) {
					String[] aypost = post.split(",");
					for (int i = 0, j = aypost.length; i < j;) {
						dos.writeBytes("-----------123");
						dos.writeShort(0x0d0a);
						dos.writeBytes("Content-Disposition: form-data; name=\"");
						dos.writeBytes(URLEncoder.encode(aypost[i++], "UTF-8"));
						dos.writeBytes("\"");
						dos.writeShort(0x0d0a);
						dos.writeShort(0x0d0a);
						dos.writeBytes(URLEncoder.encode(aypost[i++], "UTF-8"));
						dos.writeShort(0x0d0a);
					}
				}
				/*
				 * for(String key : $file.keySet() ){ String[] file =
				 * URLEncoder.encode( key, UTF8 ).split( "," ); dos.writeBytes(
				 * "-----------123" ); dos.writeShort( 0x0d0a ); dos.writeBytes(
				 * "Content-Disposition: form-data; name=\"" ); dos.writeBytes(
				 * file[0].trim() ); dos.writeBytes( "\"; filename=\"" );
				 * dos.writeBytes( file[1].trim() ); dos.writeBytes( "\"" );
				 * dos.writeShort( 0x0d0a ); dos.writeBytes(
				 * "Content-Type: application/octet-stream" ); dos.writeShort(
				 * 0x0d0a ); dos.writeShort( 0x0d0a );
				 * 
				 * InputStream is = $file.get( key ); int bytesAvailable =
				 * is.available(); int bufferSize = Math.min( bytesAvailable,
				 * 1024 ); byte[] buffer = new byte[bufferSize]; int bytesRead =
				 * is.read(buffer, 0, bufferSize); while (bytesRead > 0){
				 * dos.write(buffer, 0, bufferSize); bytesAvailable =
				 * is.available(); bufferSize = Math.min(bytesAvailable, 1024);
				 * bytesRead = is.read(buffer, 0, bufferSize); } is.close();
				 * dos.writeShort( 0x0d0a ); }
				 */

			} else if (post != null) {
				conn.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				// post 처리
				// outStream을 얻고
				OutputStreamWriter out;
				out = new OutputStreamWriter(conn.getOutputStream());

				// $post를 파싱하여 적어준다.
				String[] aypost = post.split(",");
				for (int i = 0, j = aypost.length; i < j;) {
					out.write(URLEncoder.encode(aypost[i++], "UTF-8"));
					out.write("=");
					out.write(URLEncoder.encode(aypost[i++], "UTF-8"));
				}
				out.flush();
				out.close();

			}
			conn.connect();
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				
				String encode = conn.getHeaderField("Content-encoding");
				if (encode.equalsIgnoreCase("gzip")) {
					is = new GZIPInputStream(is);
				}
				return is;
			} else {
				return null;
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
